﻿package  
{
	import as3.utils.StringUtil;
	/**
	 * ...
	 * @author hbb
	 */
	public class JapandataTvParser implements AlbumInfoParser
	{
		
		public function parser( data:String ):XiaMiAlbumInfo
		{
			data = data.toLowerCase();
			
			var artist:String, title:String, category:String, publishtime:String, songs:String;
			var description:String = '';
			var i:int = 0;
			var j:int = 0;
			
			// strict get category
			i = data.indexOf('<title>', j);
			if ( -1 == i ) throw new Error('没找到 Category');
			i += 7;
			j = data.indexOf(']', i) + 1;
			category = validCategory( trim(data.slice(i, j)) );
			
			// strict get artist
			i = data.indexOf('artist:', j);
			if ( -1 == i ) throw new Error('没找到 Artist');
			i += 7;
			j = data.indexOf('<', i);
			artist = trim(data.slice(i, j));
			
			// strict get album(title)
			i = data.indexOf('album:', j);
			if ( -1 == i ) throw new Error('没找到 Album');
			i += 6;
			j = data.indexOf('<', i);
			title = trim(data.slice(i, j));
			
			// strict get date(publishtime)
			i = data.indexOf('date:', j);
			if ( -1 == i ) throw new Error('没找到 Date');
			i += 5;
			j = data.indexOf('<', i);
			publishtime = validDate( trim(data.slice(i, j)) );
			
			// get description
			i = data.indexOf('description<br/>', j);
			if ( -1 != i )
			{
			i += 16;
			j = data.indexOf('<', i);
			description = trim(data.slice(i, j));
			}
			
			// strict get Tracklist(songs)
			i = data.search(/tracklist.?<br\/>/i);
			if ( -1 == i ) throw new Error('没找到 Tracklist');
			i += 14;
			j = data.indexOf('<br/><', i);
			songs = validTracklist( data.slice(i, j) );
			
			var info:XiaMiAlbumInfo = new XiaMiAlbumInfo(title, artist, category, XiaMiAlbumLanguage.JAPANESE, publishtime, songs);
			info.description = description;
			
			return info;
		}
		
				
		private function trim(v:String):String
		{
			var a:Array = v.split('&nbsp;');
			var s:String = a.join('');
			return StringUtil.trim(s);
		}
		
		private function validCategory(v:String):String
		{
			switch(v)
			{
				case '[single]': return XiaMiAlbumCategory.SINGLE;
				case '[album]': return XiaMiAlbumCategory.ALBUM;
				default: throw new Error('没找到正确的 Category: ' + v);
			}
		}
		
		private function validTracklist(v:String):String
		{
			var list:Array = v.split('<br/>');
			return list.join('\n');
		}
		
		private function validDate(v:String):String
		{
			var ymd:Array = v.split('-');
			var y:String = ymd[0];
			var m:String = ymd[1];
			if (m.length == 1) m = '0' + m;
			var d:String = ymd[2];
			if (d.length == 1) d = '0' + d;
			return y + '-' + m + '-' + d;
		}
		
	}
	
}